#include <iostream>
#include <vector>
using namespace std;

long long maxWater(vector<int>& arr) {
    int n = arr.size();
    int leftBound = 0, rightBound = n - 1, cur = 0;
    long long ans = 0;
    while (leftBound < rightBound) {
        if (arr[leftBound] <= arr[rightBound]) {
            cur = leftBound + 1;
            while (cur <= rightBound) {
                if (arr[cur] < arr[leftBound]) {
                    ans += arr[leftBound] - arr[cur];
                } else {
                    leftBound = cur;
                    break;
                }
                cur++;
            }
        } else {
            cur = rightBound - 1;
            while (cur >= leftBound) {
                if (arr[cur] < arr[rightBound]) {
                    ans += arr[rightBound] - arr[cur];
                } else {
                    rightBound = cur;
                    break;
                }
                cur--;
            }
        }
    }
    return ans;
}

int main() {
    vector<int> arr = {4,5,1,3,2};
    long long ans = maxWater(arr);
    cout << ans << endl;
    return 0;
}